package com.jiyuren.spring.api;


import com.jiyuren.spring.utils.FormatUtil;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * Created by Administrator on 2016/3/2.
 */
public class HttpLogInterceptor implements Interceptor {
    private static final Charset UTF8 = Charset.forName("UTF-8");

    public okhttp3.Response intercept(Chain chain) throws IOException {
        Charset charset = UTF8;
        Request request = chain.request();
        //打印请求内容
        RequestBody requestBody = request.body();
        boolean hasRequestBody = requestBody != null;

        String method = request.method();
        if (method.equalsIgnoreCase("get")) {
            System.out.println("API method = " + method + " URL = " + request.url());
        }
        if (hasRequestBody) {
            Buffer reqBuffer = new Buffer();
            requestBody.writeTo(reqBuffer);
            MediaType reqContentType = requestBody.contentType();
            if (reqContentType != null) {
                charset = reqContentType.charset(UTF8);
            }
            String params = reqBuffer.readString(charset);
            String reqParams = URLDecoder.decode(params, charset.name());
//            KLog.i("unicode2Chinese before API URL = method " + method + " " + request.url() + "&" + params);
            System.out.println("unicode2Chinese after API URL = method " + method + " " + request.url() + "&" + reqParams);
        }
        //打印返回内容
        long startNs = System.nanoTime();
        okhttp3.Response response = chain.proceed(request);
        long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
        ResponseBody responseBody = response.body();
        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE); // Buffer the entire body.
        Buffer buffer = source.buffer();
        MediaType resContentType = responseBody.contentType();
        long contentLength = responseBody.contentLength();
        if (resContentType != null) {
            try {
                charset = resContentType.charset(UTF8);
            } catch (UnsupportedCharsetException e) {
                System.out.println("Couldn't unicode2Chinese the response body; charset is likely malformed.");
                System.out.println("<-- END HTTP");
                return response;
            }
        }
        if (contentLength != 0) {
            String result = buffer.clone().readString(charset);
            String requestUrl = response.request().url().toString();
            String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
            System.out.println("result " + response.code() + " " + response.message() + " "
                    + tookMs + "sms " + bodySize + " body");
            System.out.println("requestUrl = " + requestUrl);
            if (result.startsWith("{") || result.startsWith("[")) {
//                FormatUtil.json(result);
                System.out.println("result:" + result);
            } else {
                String data = FormatUtil.unicode2Chinese(result);
                System.out.println("result:" + data);
            }
        }
        return response;
    }
}
